package com.cdks.wuxiu.api.service;


import com.cdks.wuxiu.api.component.agora.AgoraUtil;
import com.cdks.wuxiu.api.component.aliyun.AliyunConfig;
import com.cdks.wuxiu.api.component.agora.AgoraConfig;
import com.cdks.wuxiu.api.component.constant.Constant;
import com.cdks.wuxiu.api.service.mysql.CallSheetInfoService;
import com.cdks.wuxiu.api.service.redis.RedisService;
import com.cdks.wuxiu.api.util.HttpUtils;
import com.cdks.wuxiu.api.util.TimeUtils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;


/**
 * 声网服务实现类
 */
@Slf4j
@Service
public class AgoraServiceImpl implements AgoraService {
    @Resource
    private RedisService redisService;
    @Resource
    private CallSheetInfoService callSheetInfoService;    


    private JSONObject createBody(String ucid)
    {
        JSONObject body  = new JSONObject();

        body.set("cname", ucid);
        body.set("uid", String.valueOf(Constant.USERID_SYSTEM));

        return body;
    }

    private JSONObject sendAcquire(String ucid)
    {
        String url  = "https://api.sd-rtn.com/v1/apps/" + AgoraConfig.appId + "/cloud_recording/acquire";
        //HTTP消息头
        HashMap<String, String> head  = new HashMap<String, String>();
        head.put("Authorization", "Basic " + AgoraUtil.getBasicAuth());
        //HTTP消息体
        JSONObject client  = new JSONObject();
        client.set("resourceExpiredHour", 24);

        JSONObject body  = createBody(ucid);
        body.set("clientRequest", client);

        String ret  = HttpUtils.send_post_request(url, head, JSONUtil.toJsonStr(body));
        log.info("acquire: " + ret);

        return JSONUtil.parseObj(ret);
    }

    private JSONObject sendStart(String ucid, String resId)
    {
        String url  = "https://api.sd-rtn.com/v1/apps/" + AgoraConfig.appId + "/cloud_recording/resourceid/" + resId + "/mode/mix/start";
        //HTTP消息头
        HashMap<String, String> head  = new HashMap<String, String>();
        head.put("Authorization", "Basic " + AgoraUtil.getBasicAuth());
        //HTTP消息体
        HashMap<String, Object> recordingConfig  = new HashMap<String, Object>();
        recordingConfig.put("channelType", 0);
        recordingConfig.put("streamTypes", 0);
        
        JSONArray fileNamePrefix  = new JSONArray();
        fileNamePrefix.add("record");
        fileNamePrefix.add(ucid);

        JSONObject storageConfig  = new JSONObject();
        storageConfig.set("vendor", 2);
        storageConfig.set("region", 0);
        storageConfig.set("bucket", AliyunConfig.CLOUD_BUCKET_NAME);
        storageConfig.set("accessKey", AliyunConfig.CLOUD_CLIENT_KEYID);
        storageConfig.set("secretKey", AliyunConfig.CLOUD_CLIENT_SECRET);
        storageConfig.set("fileNamePrefix", fileNamePrefix);

        JSONObject client  = new JSONObject();
        client.set("token", AgoraUtil.getCallToken(String.valueOf(Constant.USERID_SYSTEM), ucid));
        client.set("recordingConfig", recordingConfig);
        client.set("storageConfig", storageConfig);

        JSONObject body  = createBody(ucid);
        body.set("clientRequest", client);

        String ret  = HttpUtils.send_post_request(url, head, JSONUtil.toJsonStr(body));
        log.info("start: " + ret);

        return JSONUtil.parseObj(ret);
    }

    private JSONObject sendStop(String ucid, String resId, String sid)
    {
        String url  = "https://api.sd-rtn.com/v1/apps/" + AgoraConfig.appId + "/cloud_recording/resourceid/" + resId + "/sid/" + sid + "/mode/mix/stop";
        //HTTP消息头
        HashMap<String, String> head  = new HashMap<String, String>();
        head.put("Authorization", "Basic " + AgoraUtil.getBasicAuth());
        //HTTP消息体
        JSONObject client  = new JSONObject();
        client.set("async_stop", true);

        JSONObject body  = createBody(ucid);
        body.set("clientRequest", client);

        String ret  = HttpUtils.send_post_request(url, head, JSONUtil.toJsonStr(body));
        log.info("stop: " + ret);

        return JSONUtil.parseObj(ret);
    }

    @Override
    public int recordStart(String ucid) {

        try
        {
            if (redisService.setRecordStart(ucid) < 0)
            {
                return -1;
            }

            JSONObject info  = sendAcquire(ucid);
            String resourceId = info.getStr("resourceId");
            if (resourceId == null)
            {
                return -2;
            }

            info  = sendStart(ucid, resourceId);
            resourceId  = info.getStr("resourceId");
            String sid  = info.getStr("sid");
            if (sid == null)
            {
                return -3;
            }

            HashMap<String, Object> data  = new HashMap<String, Object>();
            data.put("resId", resourceId);
            data.put("sid", sid);
            redisService.saveRecordInfo(ucid, data);
            callSheetInfoService.record(ucid, sid);
            
        } catch (Exception e)
        {
            log.error(e.getMessage());
        }

        return 0;
    }

    @Override
    public int recordStop(String ucid) {
        Map<Object, Object> info  = redisService.getRecordInfo(ucid);
        String resId  = (String) info.get("resId");
        String sid    = (String) info.get("sid");

        if ((resId == null) || (sid == null))
        {
            return -1;
        }

        sendStop(ucid, resId, sid);

        return 0;
    }

    @Override
    public int sipCallout(String ucid, String answer, String userId, String token) {
        try {
            String url  = "http://182.92.129.253:15680/agw?appkey=100100";
            //HTTP消息头
            HashMap<String, String> head  = null;
            //HTTP消息体
            JSONObject body  = new JSONObject();
            body.set("version", "2.0");
            body.set("event", "callOut");
            body.set("caller", "031169694076");
            body.set("callee", answer);
            body.set("appId", AgoraConfig.appId);
            body.set("channelId", ucid);
            body.set("userId", userId);
            body.set("token", token);
            body.set("expires", "86400");
            body.set("timestamp", TimeUtils.getLocalDateTime("yyyyMMddHHmmss"));
    
            String ret  = HttpUtils.send_post_request(url, head, JSONUtil.toJsonStr(body));
            log.info("callPSTN: " + ret);
            JSONObject json = JSONUtil.parseObj(ret);
            if (json == null)
            {
                return -1;
            }

            String callID  = json.getStr("callID");
            if (callID == null)
            {
                return -1;
            }
    
            callSheetInfoService.setSipId(ucid, callID);

            return 0;
        } catch (Exception e) {
            log.error(e.getMessage());

            return -1;
        }
    }

    @Override
    public int sipHangup(String callID) {
        try {
            String url  = "http://182.92.129.253:15680/agw?appkey=100100";
            //HTTP消息头
            HashMap<String, String> head  = null;
            //HTTP消息体
            JSONObject body  = new JSONObject();
            body.set("version", "2.0");
            body.set("event", "hangup");
            body.set("type", "normal");
            body.set("callID", callID);
            body.set("timestamp", TimeUtils.getLocalDateTime("yyyyMMddHHmmss"));
    
            String ret  = HttpUtils.send_post_request(url, head, JSONUtil.toJsonStr(body));
            log.info("callPSTN: " + ret);

            return 0;
        } catch (Exception e) {
            log.error(e.getMessage());

            return -1;
        }
    }
}
